package com.shareppy.normanhttp;

import com.shareppy.normanhttp.tasks.TaskCallback;
import com.shareppy.normanhttp.tasks.TaskException;

import android.app.Activity;
import android.widget.Toast;

public class ActivityTaskCallback<RESULT> implements TaskCallback<RESULT> {

	protected Activity activity;
	private boolean runOnUIThread;

	public ActivityTaskCallback(Activity activity) {
		this(activity, true);
	}

	public ActivityTaskCallback(Activity activity, boolean runOnUIThread) {
		this.activity = activity;
		this.runOnUIThread = runOnUIThread;
	}

	@Override
	public void onError(final TaskException throwable) {
		if (runOnUIThread) {
			activity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					fail(throwable);
				}
			});
		} else {
			fail(throwable);
		}
	}

	protected void fail(final TaskException throwable) {
		Toast.makeText(activity, throwable.getStatusCode()+":"+throwable.getStatusMessage(), Toast.LENGTH_LONG).show();
	}

	@Override
	public void onResponse(final RESULT response) {
		if (runOnUIThread) {
			activity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					success(response);
				}
			});
		} else {
			success(response);
		}
	}

	protected void success(RESULT response) {
		Toast.makeText(activity, (String)response, Toast.LENGTH_LONG).show();
	}
}